# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '17/10/2024'
    comment: 服务流程
"""
from fastapi import APIRouter, Query
from starlette.requests import Request
from sqlalchemy import func, or_

from config import Config
from project.core.function import json_response, if_none
from project.lib.decorator import api_common, exec_duration
from project.service.flow import FlowService
from project.model.database.flow import Flow
from project.micro_service.zeus import Zeus


flow_router = APIRouter(prefix='/u', tags=['user.flow'])


@flow_router.get('/flow/list', summary='服务流程列表')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_flow_list(request: Request,
                        organization_code: str = Query(..., title='服务流程编号'),
                        session=None):
    """
        **desc**: 服务流程列表

        **url**: http(s)://{0}.udicaria.com/u/flow/list

        **method**: GET

        **params**:

            <query>:
                organization_code: 机构编号

        **return**:json数据结构::

            {
                code: 0(成功)/非0(失败)
                message: 成功返回success, 否则返回error信息
                data:
                exec_time: 接口后端处理时长
            }
        """
    flows = await Flow.fetch_all(session, wheres=(Flow.organization_code == organization_code, ~Flow.is_deleted, ~Flow.is_template))
    items = [v.dict('code', 'name', 'title', 'introduction', 'matching_intent') for v in flows]

    return json_response(data=items)


@flow_router.get('/flow/agent/info', summary='服务记录agent信息')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_flow_agent_info(request: Request,
                              flow_code: str = Query(..., title='服务流程编号'),
                              session=None):
    """
        **desc**: 服务记录agent信息

        **url**: http(s)://{0}.udicaria.com/u/flow/agent/info

        **method**: GET

        **params**:

            <query>:
                flow_code: 服务流程编号

        **return**:json数据结构::

            {
                code: 0(成功)/非0(失败)
                message: 成功返回success, 否则返回error信息
                data: {
                    code: 服务流程编号
                    title: 服务流程名称
                    description: 服务流程介绍
                    matching_intent: 用户选择时的意愿
                    sop: 服务流程sop信息
                    parameters: 当前服务可选参数列表
                }
                exec_time: 接口后端处理时长
            }
        """
    ret_data = await FlowService.get_flow_agent_info(session, flow_code=flow_code)

    return json_response(data=ret_data)


@flow_router.get('/flow/list_page', summary='服务列表(检索)')
@api_common(doc_replace=(('{0}', Config.ENV_DOC_FIX),))
@exec_duration(add_return=True)
async def get_flow_list(request: Request,
                        filter_condition: str = Query(..., title='检索条件', description='搜索条件'),
                        page: int = Query(1, title='第几页', description='默认1'),
                        page_size: int = Query(20, title='条数', description='每页显示的条数'),
                        session=None):
    """
    **desc**: 服务列表(分页)

    **url**: http(s)://{0}.udicaria.com/u/flow/list_page

    **method**: GET

    **params**:

        <query>:
            filter_condition: 搜索条件

    **return**:json数据结构::

        {
            code: 0(成功)/非0(失败)
            message: 成功返回success, 否则返回error信息
            data: {
                code: 案例编号
                name: 案例名称
                organization_code: 组织编号
                organization_name: 组织名称
            }
            exec_time: 接口后端处理时长
        }
    """
    organization_codes = []
    if filter_condition:
        organizations = await Zeus.get_organization_list(name=filter_condition)
        organization_codes = [v['code'] for v in organizations]

    wheres = list()
    if filter_condition:
        wheres.append(or_(
            Flow.code.like(f'%{filter_condition}%'),
            Flow.name.like(f'%{filter_condition}%'),
            Flow.organization_code.in_(organization_codes)
        ))
    wheres.append(~Flow.is_deleted)
    wheres.append(~Flow.is_template)

    # num
    record = await Flow.fetch_one(session, selects=(func.count(Flow.id)), wheres=wheres)
    num = if_none(record[0], 0)

    data = await Flow.fetch_all(session,
                                wheres=wheres,
                                offset=(page - 1) * page_size,
                                limit=page_size,
                                orders=Flow.id.desc())

    # 取得关联机构信息
    organization_codes = [v.organization_code for v in data]
    organizations = await Zeus.get_organization_list(codes=list(set(organization_codes)))
    organization_name_map = {v['code']: v['name'] for v in organizations}

    items = []
    for flow in data:
        d = flow.dict('code', 'name', 'organization_code')
        d['organization_name'] = organization_name_map.get(flow.organization_code)
        items.append(d)

    ret_data = {
        'num': num,
        'items': items
    }

    return json_response(data=ret_data)
